﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void btnSelectFile1_Click(object sender, EventArgs e)
        {
            SelectFile(txtFile1);
        }

        private void btnSelectFile2_Click(object sender, EventArgs e)
        {
            SelectFile(txtFile2);
        }

        private void SelectFile(TextBox textBox)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.CheckFileExists = true;
                openFileDialog.CheckPathExists = true;
                openFileDialog.Title = "请选择文件";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    textBox.Text = openFileDialog.FileName;
                }
            }
        }

        private void btnMerge_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFile1.Text) || string.IsNullOrEmpty(txtFile2.Text))
            {
                MessageBox.Show("请先选择两个文件！");
                return;
            }
            try
            {
                // 读取文件内容（指定编码）
                string content1 = ReadFileWithEncoding(txtFile1.Text);
                string content2 = ReadFileWithEncoding(txtFile2.Text);
                string mergedContent = content1 + Environment.NewLine + content2;

                // 创建目标目录
                string dataDir = Path.Combine(Application.StartupPath, "Data");
                Directory.CreateDirectory(dataDir);

                // 生成新文件名
                string newFileName = $"merged_{DateTime.Now:yyyyMMddHHmmss}.txt";
                string newFilePath = Path.Combine(dataDir, newFileName);

                // 写入新文件（指定编码）
                File.WriteAllText(newFilePath, mergedContent, Encoding.UTF8); // 明确指定 UTF-8 编码

                lblStatus.Text = $"文件合并成功！保存路径：{newFilePath}";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败：{ex.Message}");
            }
        }

        // 辅助方法：读取文件并指定编码（可根据需求调整编码）
        private string ReadFileWithEncoding(string filePath)
        {
            // 尝试自动检测编码（更灵活），或固定为某编码（如 GBK）
            using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
    }
}
